package cn.itcast.web.controller;


import cn.com.webxml.ArrayOfString;
import cn.com.webxml.WeatherWS;
import cn.com.webxml.WeatherWSSoap;
import cn.itcast.common.utils.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import cn.itcast.vo.WeatherVo;
import cn.itcast.web.token.FaceToken;
import cn.itcast.web.token.WxToken;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.qiniu.util.Json;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;
    @Autowired
    private WeatherWS weatherWS;

    /**
     * 基于shiro登录
     */
    @RequestMapping("/login")
    public String login(String email, String password) {

        //1.判断邮箱和密码是否为空,如果为空，重新登录
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            request.setAttribute("error", "用户名或者密码不能为空");
            return "forward:login.jsp";
        }
        try {
            //2.获取工具类subject
            Subject subject = SecurityUtils.getSubject();
            //3.调用subject的login方法，进入shiro内部完成登录
            UsernamePasswordToken token = new UsernamePasswordToken(email, password);//在shiro中，将登录的用户名密码封装成功token对象
            subject.login(token);
            //4.正常执行，登录成功(数据存入session，跳转主页)
            //通过shiro框架获取当前登录的用户对象
            User user = (User) subject.getPrincipal();//获取安全数据（用户对象）
            session.setAttribute("loginUser", user);
            List modules = moduleService.findByUser(user);
            session.setAttribute("modules", modules);

            //WeatherVo weatherVo = getWeatherVo(user.getId());
            WeatherVo weatherVo = getWeatherVo();
            session.setAttribute("weather", weatherVo);
            return "home/main";
        } catch (Exception e) {
            e.printStackTrace();
            //5.抛出异常，登录失败（用户名或者密码错误）
            request.setAttribute("error", "用户名或密码错误");
            return "forward:login.jsp";
        }
    }

    @RequestMapping(name="人脸识别登录",path="/faceLogin")
    public String faceLogin(String images) {
        try {
            //调用工具类通过图片从百度查找我们自己的用户id
            String id = AipFaceHelper.faceSearch(images);
            //如果id存在，说明识别成功，需要查询数据库获取用户对象保存如session
            System.out.println(id == null);
            if (id != null) {
                //2.获取工具类subject
                Subject subject = SecurityUtils.getSubject();
                //3.调用subject的login方法，进入shiro内部完成登录
                FaceToken token = new FaceToken(id);//在shiro中，将登录的用户名密码封装成功token对象
                subject.login(token);
                //4.正常执行，登录成功(数据存入session，跳转主页)
                //通过shiro框架获取当前登录的用户对象
                User user = (User) subject.getPrincipal();//获取安全数据（用户对象）
                session.setAttribute("loginUser", user);
                List modules = moduleService.findByUser(user);
                session.setAttribute("modules", modules);

                //WeatherVo weatherVo = getWeatherVo(user.getId());
                WeatherVo weatherVo = getWeatherVo();
                session.setAttribute("weather", weatherVo);
                return "home/main";
            } else {
                request.setAttribute("error", "刷脸登录失败");
                return "forward:login.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
            //5.抛出异常，登录失败（用户名或者密码错误）
            request.setAttribute("error", "刷脸登录失败");
            return "forward:login.jsp";
        }


    }

    /**
     * 微信登录
     */
    @RequestMapping(name="微信登录",path="/weixinlogin")
    public String weixinlogin(String code) {
        String openid="";
        try {
            //根据code获取access_token和open_id
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3bdb1192c22883f3&secret=db9d6b88821df403e5ff11742e799105&code="+code+"&grant_type=authorization_code";
            //发送get请求
            Map<String, Object> map = HttpUtils.sendGet(url);
            openid = map.get("openid").toString();
            if(openid == null){
                throw new RuntimeException("空指针");
            }
            //1.获取subject
            Subject subject = SecurityUtils.getSubject();
            //2.创建token对象
            WxToken token = new WxToken(openid);//在shiro中，将登录的用户名密码封装成功token对象
            //3.完成登录
            subject.login(token);
            //4.获取安全数据
            User user = (User) subject.getPrincipal();//获取安全数据（用户对象）
            //5.存入数据到session
            session.setAttribute("loginUser", user);
            //6.查询模块信息并存入session
            List modules = moduleService.findByUser(user);
            session.setAttribute("modules", modules);
            //7.获取天气信息并存入session
            //WeatherVo weatherVo = getWeatherVo(user.getId());
            WeatherVo weatherVo = getWeatherVo();

            session.setAttribute("weather", weatherVo);
            return "home/main";
        } catch (Exception e) {
            e.printStackTrace();
            if("空指针".equals(e.getMessage()) || "".equals(openid)){
                request.setAttribute("error", "微信登录失败");
                return "forward:login.jsp";
            }
            request.setAttribute("openid", openid);
            return "forward:bindWxLogin.jsp";
        }

    }

    @RequestMapping(name="绑定微信账号到用户",path="/bindWx")
    public String bindWx(String openid,String email,String password){
        User user = userService.findByEmail(email);
        if (user!=null && user.getPassword().equals(Encrypt.md5(password,email)) ) {
            //完成微信绑定
            user.setOpenId(openid);
            userService.update(user);
            //调用密码登录
            return login(email,password);
        }else {
            request.setAttribute("error", "微信绑定失败");
            return "forward:login.jsp";
        }

    }


    /**
     * 传统登录方法
     */
//	@RequestMapping("/login")
//	public String login(String email,String password) {
//		//1.判断邮箱和密码是否为空,如果为空，重新登录
//		if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)){
//			request.setAttribute("error","用户名或者密码不能为空");
//			return "forward:login.jsp";
//		}
//		//2.根据邮箱查询用户
//		User user = userService.findByEmail(email);
//		//对用户输入的密码加密，加密之后再比较
//		password = Encrypt.md5(password,email);
//		//3.判断用户是否为空，密码是否匹配
//		if( user ==null || !user.getPassword().equals(password)) {
//			//3.1 如果用户名或者密码错误
//			request.setAttribute("error","用户名或密码错误");
//			return "forward:login.jsp";
//		}else{
//			//3.2 密码一致，登录录成功（数据存入session，跳转主页）
//			session.setAttribute("loginUser",user);
//			//获取用户的所有可操作菜单（模块）
//			List modules = moduleService.findByUser(user);
//			session.setAttribute("modules",modules);
//			return "home/main";
//		}
//	}

    //退出
    @RequestMapping(value = "/logout", name = "用户登出")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); //退出（清空登录数据）
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home() {

        return "home/home";
    }

    @RequestMapping("/getWeather")
    public @ResponseBody WeatherVo getWeatherVo() {
        //根据用户id查询城市所在城市信息
        //String city = userService.findCityById(id);
        WeatherVo weatherVo = new WeatherVo();//创建WeatherVo对象
        String city = PositionUtils.getPosition(CusAccessObjectUtil.getV4IP());
        Map map = (Map) JSON.parse(city);
        JSONObject result = (JSONObject) map.get("result");
        city = (String) result.get("city");
        city = city.replace("市","");
        WeatherWSSoap weatherWSSoap = weatherWS.getWeatherWSSoap();
        //获取天气信息
        List<String> weatherList = weatherWSSoap.getWeather(city, null).getString();

        //获取详细天气信息
        city = weatherList.get(1); //城市
        String temperature=weatherList.get(8); //气温
        String img = weatherList.get(10); //图片
        String airQuality = weatherList.get(5); //空气质量
        airQuality = airQuality.substring(airQuality.lastIndexOf("空气质量"),airQuality.lastIndexOf("。"));
        //设置天气信息
        weatherVo.setCity(city);
        weatherVo.setTemperature(temperature);
        weatherVo.setImg(img);
        weatherVo.setAirQuality(airQuality);
        return weatherVo;
    }

    @RequestMapping("/toHome")
    public String tohome(){
        return "home/main";
    }


}

